<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<div th:replace="common/common::html"></div>
<head>
    <meta charset="UTF-8">
    <title th:text="#{role.page.title}"></title>
    <link th:href="@{/assets/css/page.css}" rel="stylesheet"/>
    <script th:inline="javascript">
        var _gridWidth;
        var _gridHeight;
        //页面自适应
        function resizePageSize(){
            _gridWidth = $(document).width()-12;/*  -189 是去掉左侧 菜单的宽度，   -12 是防止浏览器缩小页面 出现滚动条 恢复页面时  折行的问题 */
            _gridHeight = $(document).height()-65-40; /* -32 顶部主菜单高度，   -90 查询条件高度*/
        }

        $(function () {
            resizePageSize();
            var _columnWidth = (_gridWidth-150)/3;
            $("#flexigrid-id").flexigrid({
                width : _gridWidth,
                height : _gridHeight,
                url : /*[[@{/role/queryRoleInfoListByPage}]]*/"",
                dataType : 'json',
                colModel : [
                    {display : 'roleUuid',name : 'roleUuid',width : 150,sortable : false,align : 'center',hide : 'true'},
                    {display : /*[[#{role.name}]]*/"",name : 'roleName',width : _columnWidth, sortable : true,align : 'center'},
                    {display : /*[[#{role.remarks}]]*/"",name : 'remarks',width : _columnWidth, sortable : true,align : 'center'},
                    {display : /*[[#{common.operation}]]*/"",name : 'roleUuid',width : _columnWidth, sortable : true,align : 'center',process: function(v,_trid,_row) {
                            var html = '<div>'
                            html += `<a href="#" class="btn" onclick="modifyRoleInfo('${v}')" title=[[#{common.modify}]]><i class="glyphicon glyphicon-pencil"></i></a>`
                            html += `<a href="#" class="btn" onclick="deleteRoleInfo('${v}','${_row.roleName}')" title=[[#{common.delete}]]><i class="glyphicon glyphicon-trash"></i></a>`
                            html += `<a href="#" class="btn" onclick="allocatePermission('${v}')" title=[[#{role.allocate.permission}]]><i class="glyphicon glyphicon-share"></i></a>`
                            // 新增：角色详情按钮
                            html += `<a href="#" class="btn" onclick="showRoleUsers('${v}')" title=[[#{role.detail}]]><i class="glyphicon glyphicon-list"></i></a>`
                            html += '</div>'
                            return html;
                        }
                    },
                ],
                resizable : false, //resizable table是否可伸缩
                useRp : true,
                usepager : true, //是否分页
                autoload : false, //自动加载，即第一次发起ajax请求
                hideOnSubmit : true, //是否在回调时显示遮盖
                showcheckbox : true, //是否显示多选框
                rowhandler : rowDbclick, //是否启用行的扩展事情功能,在生成行时绑定事件，如双击，右键等
                rowbinddata : true
            });
            query()
            /**
             * 修改角色
             */
            $("#modify-role-dialog-id").dialog({
                autoOpen : false,
                width : 400,
                modal : true,
                resizable : false,
                title: /*[[#{role.modify.dialog.title}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function() {
                            var flag = $("form#modify-role-form-id input.form-control").checkDom()
                            if(!flag){
                                return
                            }
                            $("#modify-role-form-id").submit()
                        }
                    },//end button
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    }//end buttons
                ]
            })//end dialog
            /**
             * 修改角色异步表单
             */
            $("#modify-role-form-id").ajaxForm({
                dataType: "json",
                success : function(data) {
                    message(data.msg);
                    query();
                    if (data.success){
                        $("#modify-role-dialog-id").dialog('close')
                    }
                },
                error : function() {
                    message(/*[[#{common.error}]]*/'');
                },
            })//end ajaxForm


            /**
             * 增加角色对话框
             */
            $("#add-role-dialog-id").dialog({
                autoOpen : false,
                width : 400,
                modal : true,
                resizable : false,
                title: /*[[#{role.add.dialog.title}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function() {
                            var flag = $("form#add-role-form-id input.form-control").checkDom()
                            if(!flag){
                                return
                            }
                            $("#add-role-form-id").submit()
                        }
                    },//end button
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    }//end buttons
                ]
            })
            /**
             * 增加角色异步表单
             */
            $("#add-role-form-id").ajaxForm({
                dataType: "json",
                success : function(data) {
                    message(data.msg);
                    query();
                    if (data.success){
                        $("#add-role-dialog-id").dialog('close')
                    }
                },
                error : function() {
                    message(/*[[#{common.error}]]*/'');
                },
            })//end ajaxForm


            //删除角色对话框
            $("#delete-role-dialog-id").dialog({
                autoOpen : false,
                width : 400,
                modal : true,
                resizable : false,
                title: /*[[#{role.delete.dialog.title}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function() {
                            var ids = $("#delete-role-dialog-id").attr("ids")
                            $.ajax({
                                type: 'post',
                                async: false,
                                dataType : 'json',
                                url: /*[[@{/role/deleteRoleByIds}]]*/'',
                                data: [{name:"ids",value:ids}],
                                success: function (data) {
                                    message(data.msg)
                                    if (data.success){
                                        $("#delete-role-dialog-id").dialog('close')
                                        query()
                                    }

                                },
                                error: function(msg){
                                    message(/*[[#{common.error}]]*/'');
                                }
                            });
                        }
                    },//end button
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    }//end buttons
                ]
            });

            //分配权限对话框
            $("#allocate-permission-dialog-id").dialog({
                autoOpen : false,
                width : 400,
                modal : true,
                resizable : false,
                title: /*[[#{role.allocate.permission.dialog}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function() {
                            let roleUuidArray = $("#allocate-permission-dialog-id").attr('ids')
                            let menuIdArray = []
                            let treeObj = $.fn.zTree.getZTreeObj("allocate-permission-ztree-id")
                            let nodes = treeObj.getCheckedNodes(true)
                            $(nodes).each(function (index,item) {
                                menuIdArray.push(item.id)
                            })
                            $.ajax({
                                type: 'post',
                                async: false,
                                dataType : 'json',
                                url: /*[[@{/role/saveRoleRefMenu}]]*/'',
                                data: [
                                    {name:"menuIdArray",value:menuIdArray},
                                    {name:"roleUuidArray",value:roleUuidArray},
                                ],
                                success: function (data) {
                                    message(data.msg)
                                    if (data.success){
                                        $("#allocate-permission-dialog-id").dialog('close')
                                    }
                                },
                                error: function(msg){
                                    message(/*[[#{common.error}]]*/'');
                                }
                            });
                        }
                    },//end button
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    }//end buttons
                ]
            })

            // 新增：角色详情对话框初始化
            $("#role-users-dialog-id").dialog({
                autoOpen: false,
                width: 800,
                modal: true,
                resizable: false,
                title: /*[[#{role.detail.dialog.title}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.close}]]*/'',
                        click: function() {
                            $(this).dialog("close");
                        }
                    }
                ]
            });


            $("#role-users-grid").flexigrid({
                width: 750,
                height: 400,
                url: /*[[@{/role/queryUsersByRoleUuid}]]*/'',
                dataType: 'json',
                colModel: [
                    {display: /*[[#{user.name}]]*/'', name: 'userName', width: 180, sortable: true, align: 'center'},
                    {display: /*[[#{user.nice.name}]]*/'', name: 'niceName', width: 180, sortable: true, align: 'center'},
                    {display: /*[[#{user.mobile}]]*/'', name: 'mobile', width: 180, sortable: true, align: 'center'},
                    {display: /*[[#{user.email}]]*/'', name: 'email', width: 200, sortable: true, align: 'center'}
                ],

                resizable: false,
                useRp: true,
                usepager: true,
                autoload: false
            });

        })//end ready function

        function query() {
            var roleName = $("#role-name-id").val()
            $("#flexigrid-id").flexOptions({
                extParam:[
                    {name:"roleName",value:roleName}
                ]

            }).flexReload()
        }
        //双击事件
        function rowDbclick(r){
            $(r).dblclick(
                function() {
                    var columnsArray = $(r).attr('ch').split("_FG$SP_");
                    var roleUuid = columnsArray[0]
                    modifyRoleInfo(roleUuid);
                });
        }

        /**
         * 修改角色信息
         * @param roleUuid
         */
        function modifyRoleInfo(roleUuid) {
            $.ajax({
                    type: 'post',
                    async: false,
                    dataType : 'json',
                    url: /*[[@{/role/queryRoleInfoById}]]*/'',
                    data: [{name:"roleUuid",value:roleUuid}],
                    success: function (data) {
                        var list = $("form#modify-role-form-id input.form-control")
                        list.each(function (index,item) {
                            var name = $(item).attr("name")
                            $(this).val(data[name])
                        })

                        $("form#modify-role-form-id input.form-control").checkDom()
                        $("#modify-role-dialog-id").dialog('open')

                    },
                    error: function(msg){
                        message(/*[[#{common.error}]]*/'');
                    }
                }
            );
        }

        //增加角色
        function addRole() {
            $("form#add-role-form-id input.form-control").removeClass('ui-state-error');
            $("#add-role-form-id").resetForm();
            $("#add-role-dialog-id").dialog('open')
        }//end add role

        //删除角色
        function bathDeleteRole() {
            var ids = $("#flexigrid-id").getFlexigridiAttrByIndex(0)
            if(ids.length === 0){
                message(/*[[#{common.empty}]]*/'');
                return;
            }

            $("#delete-role-dialog-id").attr('ids',ids)
            var niceNameArray = $("#flexigrid-id").getFlexigridiAttrByIndex(1)
            $("#delete-role-list-id").text(niceNameArray.join(","))
            $("#delete-role-dialog-id").dialog('open')
        }
        //单独删除角色
        function deleteRoleInfo(roleUuid,roleName) {
            $("#delete-role-dialog-id").attr('ids',roleUuid)
            $("#delete-role-list-id").text(roleName)
            $("#delete-role-dialog-id").dialog('open')
        }

        var allocateSetting = {
            check: {
                enable: true
            },
            data: {
                simpleData: {
                    enable: true
                }
            }
        };

        //批量分配权限
        function bathAllocatePermission() {
            var ids = $("#flexigrid-id").getFlexigridiAttrByIndex(0)
            if(ids.length === 0){
                message(/*[[#{common.empty}]]*/'');
                return;
            }
            allocatePermission(ids)
        }

        //分配权限
        function allocatePermission(roleUuid) {
            $("#allocate-permission-dialog-id").attr('ids',roleUuid)
            $.ajax({
                type: 'post',
                async: false,
                dataType : 'json',
                url: /*[[@{/role/queryMenuTreeListByRole}]]*/'',
                data: [{name:"roleUuid",value:roleUuid}],
                success: function (data) {
                    $.fn.zTree.init($('#allocate-permission-ztree-id'),allocateSetting,data)
                    $("#allocate-permission-dialog-id").dialog('open')
                },
                error: function(msg){
                    message(/*[[#{common.error}]]*/'');
                }
            });
        }

        // 新增：显示角色关联的用户列表
        function showRoleUsers(roleUuid) {
            // 初始化用户列表表格
            // $("#role-users-grid").flexigrid({
            //     width: 750,
            //     height: 400,
            //     url: /*[[@{/role/queryUsersByRoleUuid}]]*/'',
            //     dataType: 'json',
            //     colModel: [
            //         {display: /*[[#{user.name}]]*/'', name: 'userName', width: 180, sortable: true, align: 'center'},
            //         {display: /*[[#{user.nice.name}]]*/'', name: 'niceName', width: 180, sortable: true, align: 'center'},
            //         {display: /*[[#{user.mobile}]]*/'', name: 'mobile', width: 180, sortable: true, align: 'center'},
            //         {display: /*[[#{user.email}]]*/'', name: 'email', width: 200, sortable: true, align: 'center'}
            //     ],
            //     extParam: [{name: "roleUuid", value: roleUuid}],
            //     resizable: false,
            //     useRp: true,
            //     usepager: true,
            //     autoload: false
            // });
            $("#role-users-grid").flexOptions({
                extParam:[
                    {name:"roleUuid",value:roleUuid}
                ]

            }).flexReload()
            // 打开对话框
            $("#role-users-dialog-id").dialog('open');
        }

    </script>

</head>
<body>
<header>
    <input id="role-name-id" th:placeholder="#{role.name.plc}">

    <a href="#" class="btn-info btn" onclick="query()">
        <i class=" glyphicon glyphicon-search"></i>
        <span th:text="#{common.query}"></span>
    </a>

    <a href="#" class="btn-info btn" onclick="addRole()">
        <i class=" glyphicon glyphicon-plus"></i>
        <span th:text="#{common.add}"></span>
    </a>

    <a href="#" class="btn-info btn" onclick="bathDeleteRole()">
        <i class=" glyphicon glyphicon-trash"></i>
        <span th:text="#{common.delete}"></span>
    </a>

    <a href="#" class="btn-info btn" onclick="bathAllocatePermission()">
        <i class=" glyphicon glyphicon-share"></i>
        <span th:text="#{role.allocate.permission}"></span>
    </a>

</header>
<table id="flexigrid-id"></table>
<div id="modify-role-dialog-id" style="display: none">
    <form id="modify-role-form-id" method="post" th:action="@{/role/modifyRoleInfoById}">
        <div class="form-group" >
            <span th:text="#{role.uuid}"></span>
            <input class="form-control" name="roleUuid" readonly>
        </div>

        <div class="form-group" >
            <span th:text="#{role.name}"></span>
            <input class="form-control" name="roleName" pattern="^.{4,}$">
        </div>


        <div class="form-group" >
            <span th:text="#{role.remarks}"></span>
            <input class="form-control" name="remarks"  pattern="^.*$">
        </div>


    </form>
</div>


<div id="add-role-dialog-id" style="display: none">
    <form id="add-role-form-id" method="post" th:action="@{/role/addRoleInfoById}">

        <div class="form-group" >
            <span th:text="#{role.name}"></span>
            <input class="form-control" name="roleName"
                   th:placeholder="#{role.name.plc}"
                   pattern="^.{4,}$">
        </div>


        <div class="form-group" >
            <span th:text="#{role.remarks}"></span>
            <input class="form-control" name="remarks"
                   th:placeholder="#{role.remarks.plc}"
                   pattern="^.*$">
        </div>
    </form>
</div>

<div id="delete-role-dialog-id" style="display: none">
    <span id="delete-role-list-id"></span>
</div>

<div id="allocate-permission-dialog-id" style="display: none">
    <ul id='allocate-permission-ztree-id' class="ztree"></ul>
</div>

<!-- 新增：角色详情对话框 -->
<div id="role-users-dialog-id" style="display: none">
    <table id="role-users-grid"></table>
</div>

</body>
</html>
